package com.markhsiu.httpserver.event.formparse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.markhsiu.common.ConstantUtil;
import com.markhsiu.httpserver.event.Request;

/**
 * 普通表单解析
 * 
 * 数据格式
 * =========================================================================
 * username=123123&name=12312
 * =========================================================================
 */
public class ComonFormParse {

	private static final int DEFAULT_BUFSIZE = 2048;
	private Map<String, String> params = new HashMap<String, String>();
	private Request request;
	private byte[] data;

	public ComonFormParse(Request request) {
		this.request = request;
	}

	public ComonFormParse execute() throws UnsupportedEncodingException {
		data = read();
		StringBuilder sb = new StringBuilder();
		for (byte b : data) {
			sb.append((char) b);
		}
		parseParam(sb.toString());
		return this;
	}

	public Map<String, String> getResult() {
		return params;
	}

	private void parseParam(String paramStr) throws UnsupportedEncodingException {
		String[] paramArray = paramStr.split("&");
		
			for (String param : paramArray) {
				if (param.length() > 1) {
					String[] ps = param.split("=");
					params.put(ps[0], ps.length > 1 ? ConstantUtil.decodeUTF(ps[1]) : "");
				}
			}
		
	}

	private byte[] read() {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		InputStream input = request.getInputStream();
		try {

			byte[] buff = new byte[DEFAULT_BUFSIZE];
			int rc = 0;
			while (true) {
				rc = input.read(buff, 0, DEFAULT_BUFSIZE);
				data.write(buff, 0, rc);
				if (rc < DEFAULT_BUFSIZE) {
					break;
				}
			}
		} catch (IOException ee) {
			ee.printStackTrace();
		}
		return data.toByteArray();
	}
}
